package com.ay.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
      String url=httpServletRequest.getRequestURI();

        if(url.indexOf("/tologin")>=0||url.indexOf("/login")>=0){
            return  true;
        }

        HttpSession session = httpServletRequest.getSession();
        Object obk = session.getAttribute("user");
        if(obk!=null)
            return true;

        httpServletRequest.setAttribute("msg","还没登录,请先登录");
       httpServletRequest.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(httpServletRequest,httpServletResponse);

        String contextPath = httpServletRequest.getContextPath();  //当前项目发布路径
        System.out.println(contextPath);
      //  httpServletResponse.sendRedirect(contextPath+"/WEB-INF/views/login.jsp");
        //这里的静态资源可以访问 因为已经过了 Disparchservlet    要不然要配置文件   浏览器直接http://localhost:8080//WEB-INF/views/login.jsp是访问不到的
       //拦截器出现在Disparchservlet之后  ，进入controller之前
        //静态资源被拦截也是因为Disparchservlet的作用
        //这里是请求转发   如果是请求重定向也不可以
        //  请求重定向会被Disparchservlet再次拦截
        System.out.println(1111111);
        return false;


    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
